package com.lanou.Utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {


    private static SqlSessionFactory sqlSessionFactory;

    public  static  SqlSessionFactory getSqlSessionFactory(){
        return getSqlSessionFactory("mybatis_conf.xml");
    }

    public  static  SqlSessionFactory getSqlSessionFactory(String configPath) {
        return getSqlSessionFactory(configPath,null);
    }


    public  static  SqlSessionFactory getSqlSessionFactory(String configPath,String env) {
        if (sqlSessionFactory == null) {
            synchronized (MyBatisUtils.class) {
                if (sqlSessionFactory == null) {
                    try {
                        InputStream in = Resources.getResourceAsStream(configPath);
                        if(env == null){
                            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
                        }else {
                            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in,env);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("加载核心配置文件失败");
                    }
                }
            }
        }
        return sqlSessionFactory;
    }

}
